﻿using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TrinityAPI.Tools;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;

namespace TrinityAPI.Handler
{
    public class APIRequestHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var StartTime = DateTime.Now;
            //请求处理耗时跟踪  
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            APIContext.Init();
            string requestText = null;
            string requestMediaType = request.Content?.Headers?.ContentType?.MediaType;
            if (requestMediaType == "multipart/form-data")
            {
                requestText = "multipart form data";
            }
            else
            {
                requestText = request.Content?.ReadAsStringAsync().Result;
            }
            var response = base.SendAsync(request, cancellationToken);//执行
            sw.Stop();
            long exeMs = sw.ElapsedMilliseconds;

            var responseContent = response.Result.Content;
            if (responseContent != null && !string.IsNullOrWhiteSpace(APIContext.ResponseContentType))
            {
                var objectContent = responseContent as ObjectContent;
                string[] mediaTypes = APIContext.ResponseContentType.ToLower().Split(';');
                string mediaType = mediaTypes[0].Trim(' ');
                switch (mediaType)
                {
                    case "text/plain":
                    case "text/html":
                    case "text/xml":
                    case "text/javascript":
                    case "application/xml":
                        string charSet = null;
                        string responseContentString = null;
                        if (mediaTypes.Length > 1)
                        {
                            string charSetStr = mediaTypes[1].Trim(' ');
                            if (charSetStr.StartsWith("charset="))
                                charSet = charSetStr.Substring(8);
                        }
                        if (objectContent != null && objectContent.Value != null && (objectContent.ObjectType == typeof(JToken) || objectContent.ObjectType.IsSubclassOf(typeof(JToken))))
                        {
                            if (objectContent.Value is JValue)
                                responseContentString = ((JValue)objectContent.Value).ToString();
                            else
                            {
                                if (mediaType == "text/xml" || mediaType == "application/xml")
                                {
                                    var doc = JsonConvert.DeserializeXmlNode(((JToken)objectContent.Value).ToString(Formatting.None));
                                    if (doc.FirstChild?.NodeType != System.Xml.XmlNodeType.XmlDeclaration)
                                    {
                                        var xmlDeclaration = doc.CreateXmlDeclaration("1.0", charSet ?? "utf-8", null);
                                        doc.PrependChild(xmlDeclaration);
                                    }
                                    responseContentString = doc.OuterXml;
                                }
                                else
                                {
                                    responseContentString = ((JToken)objectContent.Value).ToString(Formatting.None);
                                }
                            }
                        }
                        var stringContent = new StringContent(responseContentString);
                        var contentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mediaType);
                        if (!string.IsNullOrWhiteSpace(charSet))
                        {
                            contentType.CharSet = charSet;
                        }
                        stringContent.Headers.ContentType = contentType;
                        response.Result.Content = stringContent;
                        break;
                    case "image/gif":
                    case "image/png":
                    case "image/jpeg":
                    case "application/pdf":
                    case "application/octet-stream":
                        byte[] buffer = new byte[0];
                        if (objectContent != null && objectContent.Value != null && (objectContent.ObjectType == typeof(JToken) || objectContent.ObjectType.IsSubclassOf(typeof(JToken))))
                        {
                            JToken value = (JToken)objectContent.Value;
                            if (value.Type == JTokenType.String)
                            {
                                try
                                {
                                    string base64String = value.ToString();
                                    if (!string.IsNullOrWhiteSpace(base64String))
                                        buffer = Convert.FromBase64String(base64String);
                                }
                                catch
                                {
                                }
                            }
                            else if (value.Type == JTokenType.Bytes)
                            {
                                buffer = value.Value<byte[]>();
                            }
                        }
                        var streamContent = new ByteArrayContent(buffer);
                        streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mediaType);
                        if (APIContext.ResponseHeaders != null && APIContext.ResponseHeaders.HasValues)
                        {
                            foreach (var item in APIContext.ResponseHeaders)
                            {
                                if (item.Key.Equals("content-length", StringComparison.OrdinalIgnoreCase))
                                    streamContent.Headers.Add(item.Key, buffer.Length.ToString());
                                else
                                    streamContent.Headers.Add(item.Key, item.Value.ToString());
                            }
                        }
                        response.Result.Content = streamContent;
                        break;
                }
            }

            try
            {
                JToken header = APIHelper.GetRequestHeaders(request);
                LogHelper.Info(new
                {
                    url = request.RequestUri.AbsoluteUri,
                    header = header.ToString(Formatting.None),
                    request = APIContext.LogRequest ? requestText : "request log disabled",
                    response = APIContext.LogResponse ? response.Result.Content?.ReadAsStringAsync().Result : "response log disabled",
                    status = response.Result.StatusCode,
                    startTime = StartTime,
                    duration = exeMs + "ms"
                });
                if (APIContext.ScriptEngine != null)
                    APIContext.ScriptEngine.Dispose();
            }
            catch
            { }

            return response;
        }
    }
}